package com.chengqs.tomdog.engine;

import jakarta.servlet.*;

import java.io.IOException;

public class FilterChainImpl implements FilterChain {

    // 存储过滤器的数组
    final Filter[] filters;
    // 过滤之后要处理的Servlet
    final Servlet servlet;
    // Filter总数量
    final int total;
    // 下一个要处理的Filter[index]
    int index = 0;

    public FilterChainImpl(Filter[] filters, Servlet servlet) {
        this.filters = filters;
        this.servlet = servlet;
        this.total = filters.length;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (index < total) {
            // 依次执行Filter
            int current = index;
            index++;
            // 调用下一个Filter处理:
            filters[current].doFilter(request, response, this);
        } else {
            // 调用Servlet处理:
            // 调用Servlet的service方法，实际上是自己写的继承自HttpServlet的类会调用HttpServlet的service方法，HttpServlet中又会调用重写的doGet()方法，或者doPost()方法
            servlet.service(request, response);
        }
    }
}
